package com.heima.leetcode.practice;

import org.springframework.core.io.Resource;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 165. 版本号比较
 * @date 2025/9/13 12:15
 */
public class E165 {

    /**
     * 思路：
     * 1. 拆分字符串
     * 2. 去掉多余的0
     * 3. 比较
     * @param version1 待比较的版本号
     * @param version2 待比较的版本号
     * @return 比较结果
     */
    public int compareVersion(String version1, String version2) {
        String[] version1List = version1.split("\\.");
        String[] version2List = version2.split("\\.");

        // 可以不要
        // removeZero(version1List);
        // removeZero(version2List);

        int length1 = version1List.length, length2 = version2List.length;
        int maxLength = Math.max(length1, length2);
        for(int i = 0; i < maxLength; i++){
            String vStr1 = i >= length1 ? "0" : version1List[i];
            String vStr2 = i >= length2 ? "0" : version2List[i];
            int v1 = Integer.parseInt(vStr1);
            int v2 = Integer.parseInt(vStr2);
            if(v1 < v2) return -1;
            else if(v2 < v1) return 1;
            else continue;
        }
        return 0;
    }

    /**
     * 去掉多余的0
     * @param versionList 版本号列表
     */
    private void removeZero(String[] versionList){
        boolean hasNum = false;
        for(String str : versionList){
            char[] charArray = str.toCharArray();
            StringBuilder builder = new StringBuilder();
            for(char c : charArray){
                if(c == '0' && !hasNum) continue;
                builder.append(c);
                hasNum = true;
            }
            str = builder.toString();
        }
    }
}
